package kr.co.bettersoft.sendme.rest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import kr.co.bettersoft.sendme.provider.SendMeBlock;
import kr.co.bettersoft.sendme.provider.SendMeInstall;
import kr.co.bettersoft.sendme.provider.SendMeMember;
import kr.co.bettersoft.sendme.util.SendMeCommon;
import kr.co.bettersoft.sendme.util.SendMeConstant;
import android.util.Log;

public class SendMeVersionRest {

	public static String TAG = SendMeVersionRest.class.getSimpleName();
	
	/**
	 * 최신 릴리즈 버전을 가져 온다.
	 * 
	 * @param sendMeBlock
	 * @return
	 */
	public String getLastReleasedVersion() {
		Log.i(TAG, "getLastReleasedVersion");
		
		String url = SendMeConstant.SERVER_URL
			+ SendMeConstant.MAPPING_CONTROLLER
			+ SendMeConstant.VERSION_CONTROLLER
			+ SendMeConstant.GET_LAST_RELEASED_VERSION;
		
		String resultStr = "";
		try {
			resultStr = this.requestToServer(url, "");
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return resultStr;
	}
	
	

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	
	
	/**
	 * http protocal 을 사용하는 서버 요청 공통 메소드.
	 * 요청 후 결과를 json string 으로 받아서 반환 한다.
	 * 
	 * @param url
	 * @param inputJsonString
	 * @return
	 */
	public String requestToServer(String url, String inputJsonString) {
		Log.i(TAG, "requestToServer");
		
		String result = "";
		
		try {
			URL postUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(inputJsonString.getBytes());
	        os.flush();
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	        		result = bufferedReader.readLine();
	        	}
	        }
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
}
